﻿using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using Infrastructure.CurrentData;
using Microsoft.Practices.Composite.Events;

namespace Infrastructure.ViewModels
{
    /// <summary>
    /// All links viewmodel
    /// </summary>
    public class AllLinksViewModel  : DataModel
    {
        ObservableCollection<LinkViewModel> _links = new ObservableCollection<LinkViewModel>();

        /// <summary>
        /// Gets or sets the links.
        /// </summary>
        /// <value>The links.</value>
        public ObservableCollection<LinkViewModel> Links
        {
            get
            {
                VerifyCalledOnUIThread();
                return _links;
            }
            set
            {
                VerifyCalledOnUIThread();
                if (_links != value)
                {
                    _links = value;
                    OnPropertyChanged("Categories");
                }
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AllLinksViewModel"/> class.
        /// </summary>
        public AllLinksViewModel(IEventAggregator eventAggregator) : base(eventAggregator)
        {
            State = ModelState.Fetching;

            RefreshLinks();
        }

        /// <summary>
        /// Refreshes the links.
        /// </summary>
        void RefreshLinks()
        {
            if (!ThreadPool.QueueUserWorkItem(FetchLinksCallback))
            {
                State = ModelState.Invalid;
            }
        }

        /// <summary>
        /// Fetches the links.
        /// </summary>
        /// <param name="state">The state.</param>
        void FetchLinksCallback(object state)
        {
            IDatabase database = Current.Container.Resolve<IDatabase>();
            var unitOfWork = database.CreateUnitOfWork();

            try
            {
                IRepository<Link> repository = new LinkRepository(unitOfWork);
                var links = repository.All;

                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            Links.Clear();
                                            foreach (var link in links)
                                            {
                                                Links.Add(new LinkViewModel(EventAggregator, link));
                                            }

                                            unitOfWork.Dispose();

                                            State = ModelState.Active;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);
            }
            catch (Exception e)
            {
                Log.Error("Failed to load Links", e);

                unitOfWork.Dispose();
                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            State = ModelState.Invalid;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);

            }
        }
    }
}